import React, { useEffect, useRef, useState } from "react";
import { Layout, Drawer, Tooltip, message } from 'antd';
import { history, Prompt } from 'umi';
import styles from './Welcome.less'
import { ArrowLeftOutlined, EyeOutlined, UploadOutlined, EyeFilled, SwapRightOutlined, SwapLeftOutlined, SaveOutlined, SaveFilled } from '@ant-design/icons'
import IconFont from '@/components/IconFont'
import Atemp from "@/components/ATemp";
import Atempconfig from "@/components/Atempconfig";
import Alayer from "@/components/Alayer";
import Apage from "@/components/Apage";
import AText from "@/components/AText";
import ACharts from "@/components/ACharts";
import APic from "@/components/APic";
import Asharpe from "@/components/Asharpe";
import Atable from "@/components/Atable";


import { getFetch, postFetch } from "@/utils/doFetch";
import moment from "moment";
import InitForm from "@/components/InitForm";


const { Header, Footer, Sider, Content } = Layout,
  menulist = [
    {
      title: "文本",
      icon: "icon-type-text",
      fontSize: 20,
      render: (props) => {
        return <AText {...props}></AText>
      },
    },
    {
      title: "图表",
      icon: "icon-bar_chart_",
      fontSize: 20,
      render: (props) => {
        return <ACharts {...props}></ACharts>
      },
    },
    {
      title: "表格",
      icon: "icon-table",
      fontSize: 18,
      render: (props) => {
        return <Atable {...props}></Atable>
      },
    },
    {
      title: "图片",
      icon: "icon-picture",
      fontSize: 22,
      render: (props) => {
        return <APic {...props}></APic>
      },
    },
    {
      title: "图形",
      icon: "icon-shape-fill",
      fontSize: 22,
      render: (props) => {
        return <Asharpe {...props}></Asharpe>
      },

    },
    {
      title: "模板",
      icon: "icon-template-f",
      fontSize: 18,
      index: 0,
      render: (props) => {
        return <Atemp {...props}></Atemp>
      },
    },
  ];

const Welcome = ({ location }) => {
  const [focus, setfocus] = useState("");//hover css
  const [cur, setCur] = useState(location.query);
  const [config, setconfig] = useState({

  });//config
  const [collapsed, setcollapsed] = useState(false);//展开收起
  const [item, setitem] = useState(menulist[0]);//选中工具栏
  const [layer, setlayer] = useState(false);//图层展开收起
  const [visible, setvisible] = useState(false);


  useEffect(() => {
    let noleave = window.addEventListener('beforeunload', (event) => {
      // Cancel the event as stated by the standard.
      event.preventDefault();
      // Chrome requires returnValue to be set.
      event.returnValue = '你确定要离开么？';
      
    });
    //获取当前模板配置
    getFetch({ url: `/api/template/${cur.id}`, params: {} }).then(res => {
      if (res.code == 0) {
        let datas = res?.data ?? {};
        let { name, id, size } = datas;
        if (datas?.config?.id) {
          setconfig({
            ...datas?.config,
            width: size?.width,
            height: size?.height,
            unit: size?.unit,
          });
        } else {
          setconfig(() => {
            return {
              title: name,
              id: id,
              width: size?.width,
              height: size?.height,
              unit: size?.unit,
              pages: [
                {
                  id: moment().valueOf(),
                  active: true,
                  backgroundColor: "#FFFFFF",
                  width: size?.width,
                  height: size?.height,
                  unit: size?.unit,
                }
              ]
            }
          })
        }
        setlayer(true)
      }
    })
    return noleave
  }, [cur])

  //state 操作
  const configprops = {
    config,
    setconfig,
    collapsed,
    layer,
    setlayer,
    setCur
  }

  let saveconfig = () => {
    postFetch({ url: "/api/template/save_template", params: { id: cur.id, config }, method: "PUT" }).then(res => {
      if (res.code == 0) {
        message.success(`模板：${config.title} 保存成功`);
      }
    })
  }


  return (
    <div style={{ height: "100%", overflow: 'hidden' }}>
      <Prompt message="你确定要离开么？" />
      <Layout style={{ height: "100%", minHeight: "100px", position: "absolute", width: "100%" }}>
        <Header style={{ padding: 0, backgroundColor: "#FFF", borderBottom: "1px solid #f0f0f0", height: 60 }}>
          <div className="center" style={{ justifyContent: "space-between", height: "100%" }}>
            <div className={styles.left}>
              <a style={{ fontSize: 16 }} onClick={() => {
                history.go(-1)
              }}>
                <ArrowLeftOutlined />
                <span>返回</span>
              </a>
              <img src={require("@/assets/logo_main.png")} alt="" />
            </div>
            <div className="center" style={{ fontSize: 16 }}>
              <span>
                模板：{config?.title}
              </span>
            </div>
            <div className={styles.right}>
              <a style={{ fontSize: 16 }}
                onMouseEnter={() => {
                  setfocus("SAVE")
                }}
                onMouseLeave={() => {
                  setfocus("")
                }}
                onClick={saveconfig}
              >
                {
                  focus == "SAVE" ? <SaveFilled /> : <SaveOutlined />
                }
                <span>保存</span>
              </a>
              <a className="center" style={{ backgroundColor: "#25bd64", fontSize: 16, color: "#fff" }}
                onMouseEnter={() => {
                  setfocus("PDF")
                }}
                onMouseLeave={() => {
                  setfocus("")
                }}
                onClick={() => {
                  console.log(config);
                  setvisible(true);
                }}
              >
                {
                  focus == "PDF" ? <EyeFilled /> : <EyeOutlined />
                }
                <span>预览/下载PDF</span>
              </a>
            </div>

          </div>
        </Header>
        <Layout>
          <Sider
            theme="light"
            collapsed={collapsed}
            width={240}
            style={{ position: "relative", overflow: "visible" }}
          >
            {/* 菜单 */}
            <div className={styles.menu}>
              {
                menulist.map((it, i) => {
                  return <div
                    key={i}
                    className={`${styles.menuitem} ${(item.title == it.title && !layer) ? styles.active : ''} ${(item.index - 1 == i && !collapsed && !layer) ? styles.preactive : ''}`}
                    onClick={() => {
                      setlayer(false);
                      setcollapsed(false);
                      setitem({
                        ...it,
                        index: i
                      })
                    }}>
                    <IconFont type={it.icon} style={{ fontSize: it.fontSize }}></IconFont>
                    <p>{it.title}</p>
                  </div>
                })
              }
              <div
                className={styles.menusub}
                style={{ borderTopRightRadius: collapsed || layer ? 0 : item.index == menulist.length - 1 ? 8 : 0 }}
                onDoubleClick={() => {
                  setcollapsed(!collapsed)
                }}>
                {
                  collapsed ?
                    <Tooltip title={"双击上方空白区域展开/收起"} placement="right">
                      <div className="center" onClick={() => {
                        setcollapsed(false)
                      }}>
                        <SwapRightOutlined />
                        展开
                      </div>
                    </Tooltip>
                    :
                    <Tooltip title={"双击上方空白区域展开/收起"} placement="right">
                      <div className="center" onClick={() => {
                        setcollapsed(true)
                      }}>
                        <SwapLeftOutlined />
                        收起
                      </div>
                    </Tooltip>
                }
              </div>
            </div>
            {/* 菜单内容/画布内容 */}
            <div className={styles.menuextra} style={{ width: 160 }}>
              <div style={{ position: "absolute", width: "100%", height: "100%", left: layer ? -160 : 0, transition: "all 0.2s", overflow: "hidden" }}>
                {
                  item.render?.({ ...configprops })
                }
              </div>
              <div style={{ position: "absolute", width: "100%", height: "100%", right: !layer ? -160 : 0, transition: "all 0.2s", overflow: "hidden" }}>
                <Alayer {...configprops}></Alayer>
              </div>
            </div>
            {/*画布按钮*/}
            <div className={layer ? styles.alayeract : styles.alayer} onClick={() => {
              if (!config?.id) {
                message.warn("请先添加您的模板!")
                return
              }
              setlayer(true)
              setcollapsed(false);
            }}>
              <IconFont type="icon-tuceng" style={{ fontSize: 20 }}></IconFont>
              <p>页面</p>
            </div>

          </Sider>
          <Content id="contents" className="center" style={{ position: "relative", overflow: "hidden" }}>
            <div className="center" style={{ flex: 1, height: "100%", overflow: "auto", position: "relative" }}>
              <Apage {...configprops} />
            </div>
            <Atempconfig {...configprops}></Atempconfig>

            <Drawer
              title="选择您要预览/下载的excel"
              placement="right"
              closable={false}
              onClose={() => {
                setvisible(false)
              }}
              visible={visible}
              getContainer={false}
              width={400}
              style={{ position: 'absolute', boxShadow: "none" }}
              destroyOnClose={true}
            >
              {
                visible && <InitForm
                  style={{ marginTop: -24 }}
                  fields={{
                    "file_ids": {
                      "value": null,
                      "type": "checktable",
                      "title": "",
                      "name": [
                        "file_ids"
                      ],
                      "required": true,
                      "columns": [
                        {
                          "title": "文件名称",
                          "dataIndex": "file_name",
                          "key": "file_name",
                          "ellipsis": true
                        },
                        {
                          "title": "查看",
                          "dataIndex": "file_path",
                          "key": "file_path",
                          "search": false,
                          "ellipsis": true,
                          "width": 80,
                          "renderText": (text) => {
                            return <a target="_blank" href={text}>下载文件</a>
                          }
                        }
                      ],
                      "editable": false,
                      "path": "/api/template/file_list",
                      "extraparams": { id: config.id },
                      "rowKey": "id",
                      "rowName": "file_name",
                      "tabletype": "checkbox",
                      "pagination": "false",
                      "col": {
                        "span": 24
                      }
                    },
                  }}
                  col={{ span: 24 }}
                  submitData={(values) => {
                    history.push({
                      pathname: "/preview",
                      query: {
                        ...values,
                        id: config.id,
                      }
                    })
                  }}

                ></InitForm>
              }

            </Drawer>

          </Content>
        </Layout>
      </Layout>



    </div>
  );
};

export default Welcome;
